package com.hinnotek.amoeba.ui.activity.old

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.hinnotek.amoeba.R
import com.lee.common.bean.LoginBean
import com.hinnotek.amoeba.databinding.ActivityLoginBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.utilities.*
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.viewmodels.LoginViewModel
import com.lee.common.base.BaseActivity
import com.lee.common.data.AppDatabase
import com.lee.common.data.bean.User
import com.lee.common.network.net.ObserverState
import com.lee.common.utils.*
import dagger.hilt.android.AndroidEntryPoint

/**
 * 登录Activity
 */
@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding>(), View.OnClickListener {

    private var customDialog: CustomDialog? = null

    private val viewModel by viewModels<LoginViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        setTitleBarGone()
        setLeftVisible(false)

        Skipping.start(ACTIVITY_LOGIN_NEW)
        finish()


    }

    override fun initVew() {
        bindingView.superButtonLogin.setOnClickListener(this)
    }

    override fun setData() {
        if (!TextUtils.isEmpty(SharedPreUtils.getString("userName"))) {
            bindingView.etUserAccountLogin.setText(SharedPreUtils.getString("userName"))
        }
        if (!TextUtils.isEmpty(SharedPreUtils.getString("userPassword"))) {
            bindingView.etPasswordLogin.setText(SharedPreUtils.getString("userPassword"))
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.superButton_login ->
                when {
                    TextUtils.isEmpty(bindingView.etUserAccountLogin.text.trim()) -> {
                        ToastUtils.showShort("账号不能为空！")
                        bindingView.etUserAccountLogin.requestFocus()
                    }
                    TextUtils.isEmpty(bindingView.etPasswordLogin.text.trim()) -> {
                        ToastUtils.showShort("密码不能为空！")
                        bindingView.etPasswordLogin.requestFocus()
                    }
                    else -> {
                        customDialog = CustomDialog(this, "正在登录...")
                        customDialog?.show()
                        userLoginNet()
                    }
                }
        }
    }

    /**
     * 用户登录
     */
    private fun userLoginNet() {

        val name = bindingView.etUserAccountLogin.text.trim()
        val pass = bindingView.etPasswordLogin.text.trim()
        viewModel.userLoginNet(name.toString(), pass.toString())
            .observe(this, object : ObserverState<LoginBean>() {
                override fun onDataChange(data: LoginBean) {
                    customDialog?.dismiss()
                    ToastUtils.showShort("登录成功")
                    accessToken = data.token

                    //给极光推送添加别名
                    /*val jRegistrationID: String = JPushInterface.getRegistrationID(context)
                    Timber.e(jRegistrationID)
                    JPushInterface.setAlias(context,
                        "amiba_" + data.userId,
                        object : TagAliasCallback() {
                            fun gotResult(i: Int, s: String, set: Set<String?>) {
                                Log.e("setAlias", "$s/$set")
                            }
                        })*/
                    val sharedPreferences =
                        getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE)

                    val editor = sharedPreferences.edit()
                    editor.putBoolean("isLogin", true) //登录状态
                    editor.putInt("userId", data.userId) //用户ID
                    editor.putString("userName", data.userName) //账号
                    val userPassword = bindingView.etPasswordLogin.text.toString().trim()
                    editor.putString(
                        "userPassword", userPassword
                    )
                    editor.putString("createTime", data.createTime) //注册时间
                    editor.putInt("roleId", data.roleId) //角色ID
                    editor.putString("personName", data.personName) //角色姓名
                    editor.putInt("orgId", data.orgId) //组织ID
                    editor.putString("orgName", data.orgName) //组织名称
                    editor.putString("token", data.token) //token
                    editor.putInt(isAmoebaOrCompany, data.typeId) //角色ID
                    for (dataBean in data.sysRolePriList) {
                        when (dataBean.priId) {
                            2 -> editor.putBoolean(isCompanyBusiness, true) //公司商务
                            3 -> editor.putBoolean(isCompanyFinance, true) //公司财务
                            4 -> editor.putBoolean(isPhoneNumPay, true) //手机号缴费
                            5, 9 -> editor.putBoolean(isNoticeApprove, true) //公司消息审批
                            6 -> editor.putBoolean(isAmoebaSell, true) //阿米巴销售
                            7 -> editor.putBoolean(isAmoebaTechnology, true) //阿米巴技术
                            8 -> editor.putBoolean(isAmoebaRD, true) //阿米巴研发
                            10 -> editor.putBoolean(isAmoebaStatistics, true) //阿米巴统计
                        }
                    }
                    editor.apply()

                    ToastUtils.showShort("登录成功")
                    //IntentUtils.startActivity(this@LoginActivity, MainActivity::class.java)

                    Skipping.start(ACTIVITY_WAREHOUSE_MAIN)


                    val user = User(0, data.userId, true, data.userName, userPassword,data.createTime,
                        data.roleId,data.personName,data.token,data.orgName,data.typeId,0)

                    AppDatabase.getInstance(this@LoginActivity).userDao().saveUser(user)

                    finish()
                    super.onDataChange(data)
                }

                override fun onError(msg: String?, code: Int) {
                    customDialog?.dismiss()
                    ToastUtils.showShort(msg)
                    super.onError(msg, code)
                }
            })

    }

}